import Axios from 'axios'
const state = {
	loading: [true],
	treeData: [],
	tableData: [],
	parentId: [],		//上级部门id
	lastDepartmentName: [],		//上级部门名称
	expandNodeId: null,       //要高亮展开的id
	rowId: null,		//修改id
	searchResult: [],
}
const mutations = {
    updateExpandNodeId(state, id) {         //更新要展开高亮的id
		state.expandNodeId = id ? id : null;
    },
    updateRowId(state, id) {
    	state.rowId = id ? id : null;
    },
	updateTable(state, arr) {			//更新表格数据
    	let tableData = state.tableData;
    	tableData.length = 0;
    	if(arr.length > 0) {
    		arr.forEach(item => tableData.push(item));
    	} else {
    		tableData.splice(0);
    	}
    },
    updateParentId(state, id) {
    	state.parentId.splice(0, 1, id);
    },
    updateLastDepartmentName(state, name) {
    	state.lastDepartmentName.splice(0, 1, name);
    }
}
const actions = {
	getTreeData({state, commit, dispatch, rootState}) {				//获取部门数据
		//把公司数据拼接作为最顶级节点
		if(!state.expandNodeId) {
			state.expandNodeId = rootState.systemId;
		}
		let data = {
            name: rootState.companyName,
            id: rootState.systemId,
            level: 0,
            subDepartment: []
        }
        state.loading.splice(0, 1, true);
		Axios.get('department/selectObject?systemId=' + rootState.systemId).then(res => {
			if(res.data.code == 20001) {
				state.loading.splice(0, 1, false);
				if(res.data.data && res.data.data.length > 0) {
					data['subDepartment'] = res.data.data;		//将部门数据放到公司节点上
					state.treeData.splice(0, 1, data);
					state.parentId.splice(0, 1, rootState.systemId);        //更新上级部门id
                    state.lastDepartmentName.splice(0, 1, rootState.companyName);        //更新上级部门名称
				}
				if(state.expandNodeId) {
					dispatch('getEmployeeDataByDepartmentId', state.expandNodeId);
				} else {
					dispatch('getEmployeeDataByDepartmentId', 0);
				}
			} else {
				state.loading.splice(0, 1, false);
			}
		});
	},
	getEmployeeDataByDepartmentId({state, commit, rootState}, pid) {			//通过部门id找到对应的职员
		pid = pid == rootState.systemId ? 0 : pid;
		Axios.get('employee/findEmployeeByDepartment?id=' + pid + '&systemId=' + rootState.systemId).then(res => {
			console.log(res)
			if(res.data.code == 20001) {
				if(res.data.data) {
					commit('updateTable', res.data.data);
				}
			}
		});
	},
	getSearch({state}) {
		Axios.get('employee/selectEmployeeByName').then(res => {
			if(res.data.code == 20001) {
				if(res.data.data && res.data.data.length > 0) {
					let searchResult = state.searchResult,
						data = res.data.data;
						searchResult.length = 0;
					data.forEach(item => searchResult.push(item));
				}
			}
		});
	}
}

export default {
	namespaced: true,
	state,
	mutations,
	actions
}